package control;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import model.AvailableDTO;
import model.FacilityDTO;
import business.BookingManager;

/**
 * Servlet implementation class AvailableFacilityForUpdateServlet
 */
@WebServlet(name = "AvailableFacilityForUpdate", urlPatterns = { "/AvailableFacilityForUpdate" })
public class AvailableFacilityForUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AvailableFacilityForUpdateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String period = request.getParameter("period");
		String timestamp = request.getParameter("timestamp");
		String facilityType = request.getParameter("facilityType");
		
		AvailableDTO booking = new AvailableDTO();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date dStart = null;
		try {
			dStart = df.parse(timestamp);
		} catch (ParseException e) {
			e.printStackTrace();
		}		

		BookingManager bm = new BookingManager();
		booking.setPeriod(Integer.valueOf(period));
		booking.setStartDate(dStart);
		booking.setFacilityType(facilityType);
		ArrayList<FacilityDTO> facilitylist = bm.findfacilityByCriteria(booking);
		System.out.println("size="+facilitylist.size());
		
		response.setContentType("text/html");
		
		JSONArray jsonArr = new JSONArray();
		try{
			for(FacilityDTO faci : facilitylist){
				JSONObject jso = new JSONObject();
				jso.put("id", faci.getFacilityID());
				jso.put("name", faci.getFacilityName());
				jsonArr.put(jso);				
			}
		}catch(JSONException e){
			response.getOutputStream().println("error");
		}
		System.out.print(jsonArr.toString());
		response.getOutputStream().println(jsonArr.toString());
	}
}
